package com.example.administrator.demorecyclerview.refresh;

import android.content.Context;
import android.os.Build;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.AppCompatTextView;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

/**
 * Created by Administrator on 2018/3/8.
 */

public class RefreshLoaderView extends LinearLayout implements RefreshLoader {
    public RefreshLoaderView(Context context) {
        super(context);
        init();
    }

    public RefreshLoaderView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public RefreshLoaderView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public RefreshLoaderView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init();
    }

    private TextView mTextView;

    private void init() {
        setOrientation(HORIZONTAL);

        LayoutParams paramsProgress = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        ProgressBar progressBar = new ProgressBar(getContext());
        addView(progressBar, paramsProgress);
        LayoutParams paramsText = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        mTextView = new AppCompatTextView(getContext());
        addView(mTextView, paramsText);
        setGravity(Gravity.CENTER);
    }


    @Override
    public void onThroughFooter(int distance, boolean isLoading, boolean backScrolls) {
        Log.i("@@@", "@@@onArriveFooter:" + distance + ",isLoading:" + isLoading + ",isBackScroll:" + backScrolls);
        if (!backScrolls) {
            if (!isLoading) {
                if (!loadingStarted(distance)) {
                    mTextView.setText("上拉加载更多");

                }
            }
        } else {

        }
    }


    @Override
    public void onLoadingingAccepted() {
        mTextView.setText("正在加载...");
    }

    @Override
    public boolean onStartLoading(int distance) {
        return loadingStarted(distance);
    }

    private boolean loadingStarted(int distance) {
        return distance > getMeasuredHeight() / 2;
    }

    @Override
    public void onFinishLoading() {
        mTextView.setText("加载完成");
    }
}
